package com.tanhua.app.service;

import com.tanhua.api.UserApi;
import com.tanhua.api.UserInfoApi;
import com.tanhua.app.exception.BusinessException;
import com.tanhua.app.exception.ErrorResult;
import com.tanhua.commons.utils.Constants;
import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.config.template.AipTemplate;
import com.tanhua.config.template.HuanXinTemplate;
import com.tanhua.config.template.OssTemplate;
import com.tanhua.config.template.SmsTemplate;
import com.tanhua.model.pojo.User;
import com.tanhua.model.pojo.UserInfo;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserService {

    @Autowired
    private MqMessageService mqMessageService;
    @Autowired
    private UserFreezeService userFreezeService;
    @Autowired
    private SmsTemplate smsTemplate;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private OssTemplate ossTemplate;
    @Autowired
    private AipTemplate aipTemplate;
    @Autowired
    private HuanXinTemplate huanXinTemplate;
    @DubboReference
    private UserApi userApi;
    @DubboReference
    private UserInfoApi userInfoApi;
    //发送短信验证码
    public void login(String phone) throws Exception {
        //根据手机号查询用户
        User user = userApi.findByMobile(phone);
        //判断用户是否存在,如果用户存在,就判断登录是否冻结
        if (user!=null){
            //(冻结范围) 1-冻结登录 2-冻结发言  3-冻结发布动态
            userFreezeService.freezeCheck(user.getId(),"1");
        }
        //1.生成6位数字的短信验证码
        //String code = RandomUtil.randomNumbers(6);
        //2.使用模板类发送短信验证码给手机
       // smsTemplate.sendSms(phone,code);

        String code = "123456";
        //3.把验证码保存到redis中,以后要进行校验   验证码有效时间5分钟
        redisTemplate.opsForValue().set(CHECK_CODE+phone,code, Duration.ofMinutes(5));

    }

    private String CHECK_CODE="check_code_";
    //登录校验
    public Map loginVerification(String mobile, String verificationCode) {
        //1.从redis中获取验证码
        String redisCode = redisTemplate.opsForValue().get(CHECK_CODE + mobile);

        //校验验证码,如果错误,抛异常
        //为空 或者验证码不一致 抛异常
        if (StringUtils.isBlank(redisCode)|| !redisCode.equals(verificationCode)){
            //throw  new RuntimeException("手机验证码错误");
            throw  new BusinessException(ErrorResult.loginError());
        }
        //2.根据手机号查询用户 使用dubbo服务实现数据库查询
        User user=userApi.findByMobile(mobile);

        //3.判断查询到的用户是否为空,如果为空就新增用户
        String type ="0101"; //登录操作;
        boolean isNew = false;
        if (user ==null){
            type = "0102"; //注册操作
            user = new User();

            user.setMobile(mobile);
            user.setPassword(DigestUtils.md5Hex("123456"));
            //新增用户,并返回新增用户的主键
            Long id=userApi.save(user);
            user.setId(id);

            isNew = true;
            //新用户需要自动注册环信账号和密码
            //环信账号为 hx+用户id 例如 hx1 hx106
            //环信账号密码 默认为123456
            Boolean aBoolean = huanXinTemplate.createUser(Constants.HX_USER_PREFIX + id, Constants.INIT_PASSWORD);
            if (aBoolean){ //当环信账号创建成功,更新用户表数据
                user.setHxUser(Constants.HX_USER_PREFIX + id);
                user.setHxPassword(Constants.INIT_PASSWORD);
                userApi.update(user);
            }
        }

        //4.构建token数据
        Map params = new HashMap();
        params.put("id",user.getId());
        params.put("mobile",mobile);

        String token = JwtUtils.getToken(params);

        //5.构建返回数据对象
        Map retMap= new HashMap();
        retMap.put("token",token);
        retMap.put("isNew",isNew);

        //发送操作日志的信息
        mqMessageService.sendLogMessage(user.getId(),type,"user",null);

        return retMap;
    }
    //完善用户信息
    public void loginReginfo(UserInfo userInfo) {
        userInfoApi.save(userInfo);
    }
    //上传头像
    public void upload(MultipartFile headPhoto, Long id) throws IOException {
        //1.使用阿里oss进行图片上传,返回图片URL地址
        String url = ossTemplate.upload(headPhoto.getInputStream(), headPhoto.getOriginalFilename());
        //2.使用百度aip进行图片的人脸识别
        boolean detect = aipTemplate.detect(url);
        //3.校验识别的结果,如果校验失败(图片不包含人脸),直接抛异常
        if (!detect){
            throw  new RuntimeException("图片不包含人脸");
        }
        //4.修改用户头像数据
        UserInfo userInfo = new UserInfo();
        userInfo.setId(id);
        userInfo.setAvatar(url);

        userInfoApi.updateById(userInfo);
    }
}
